
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import axios from "axios";



export function switchTime (time, format) {
  format = format ? format : 'yyyy年MM月dd日 HH:mm:ss';
  var res = format;
  var date = new Date(time);
  var timestamp = date.getTime(),
    year = date.getFullYear(),
    month = date.getMonth() + 1,
    day = date.getDate(),
    hours = date.getHours(),
    minutes = date.getMinutes(),
    seconds = date.getSeconds(),
    week = date.getDay(); // 0是星期日

  // 判断传入是否可以转换为时间
  if (!year) {
    return time;
  }
  // 替换时间戳
  res = res.replace(/timestamp/g, timestamp);
  // 替换年
  res = res.replace(/yyyy/g, year);
  // 替换月
  res = res.replace(/MM/g, makeUpNum(month));
  res = res.replace(/M/g, month);
  // 替换日
  res = res.replace(/dd/g, makeUpNum(day));
  res = res.replace(/d/g, day);
  // 替换时
  res = res.replace(/HH/g, makeUpNum(hours));
  res = res.replace(/H/g, hours);
  // 替换分
  res = res.replace(/mm/g, makeUpNum(minutes));
  res = res.replace(/m/g, minutes);
  // 替换秒
  res = res.replace(/ss/g, makeUpNum(seconds));
  res = res.replace(/s/g, seconds);
  // 替换周
  res = res.replace(/WW/g, makeUpNum(week));
  res = res.replace(/W/g, week);
  return res;
}

/**
 *数字补0
 @param {Number} val [需要补0的数]
 */
export function makeUpNum (val) {
    return val < 10 ? '0' + parseInt(val) : val;
}


export function getLabelByValue (list = [], value, empty = '', labelKey = 'label', valueKey = 'value') {
  let res = empty;
  for (var i = 0; i < list.length; i++) {
    if (list[i][valueKey] == value) {
      res = list[i][labelKey];
      break;
    }
  }
  return res;
}

// 格式化url参数
export function getQueryString() {
    const params = new URLSearchParams(location.search);
    const searchParamsObj = {};

    for (const [key, value] of params) {
      searchParamsObj[key] = value;
    }
    return searchParamsObj;
}

/**
 * 处理消息，返回类型与文本
 **/
export const formatMessage = function (message) {
  try {
    message = JSON.parse(message);
  } catch(err) {
    message = {
      type: 'TEXT',
      value: message
    }
  }
  return message;
}

/**
 * 获取唯一ID
 * @param {Number} length [随机数长度]
 * */
export function getId(length = 5) {
  return Number(Math.random().toString().substr(3, length) + Date.now().toString());
}

// 非ie浏览器下执行
export const tableToExcel = (function() {
  // 编码要用utf-8不然默认gbk会出现中文乱码
  let uri = 'data:application/vnd.ms-excel;base64,';
  let template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>{table}</body></html>';
  let base64 = function(s) {
    return window.btoa(unescape(encodeURIComponent(s)));
  }
  let format = (s, c) => {
    return s.replace(/{(\w+)}/g, (m, p) => {
      return c[p];
    })
  }
  return (table, name) => {
    let ctx = {
      worksheet: name,
      table
    }
    if (navigator.userAgent.indexOf("Firefox") > -1) {
      window.location.href = uri + base64(format(template, ctx))
    } else {
      //创建下载
      let link = document.createElement('a');
      link.setAttribute('href', uri + base64(format(template, ctx)));
      link.setAttribute('download', name);
      // window.location.href = uri + base64(format(template, ctx))
      link.click();
    }
  }
})()


/**
 * 导入文件内容
 * @param {String} path [文件路径]
 * */
export const ImportFile = function (path) {
  return new Promise((resolve, reject) => {
    axios.get(path).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject();
    })
  })
}

/**
 * 等待时间
 * @param {String} time [等待的时间]
 **/
export const waitTimeout = function (time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, time);
  })
}

// 复制文本到剪贴板
export function copyToClipboard(text) {
  // 检查浏览器是否支持 Clipboard API
  if (!navigator.clipboard) {
    // 如果不支持，则使用传统的 document.execCommand("copy") 方式
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    document.execCommand("copy");
    document.body.removeChild(textArea);
    return;
  }
 
  // 使用 Clipboard API 复制内容到剪切板
  navigator.clipboard.writeText(text).then(
    function() {
      console.log("复制成功");
    },
    function() {
      console.log("复制失败");
    }
  );
}


/**
 * DOM节点导出为PDF，如果存在is-horizontal属性为横向导出
 * @param {Object} dom [DOM节点]
 * @param {String} pdfname [pdf名称]
 * */
export function downloadPDF(dom, pdfname) {
  var isHorizontal = dom.querySelector('[is-horizontal]') ? true : false;
  html2canvas(dom).then(async (canvas) => {
    const image = canvas.toDataURL('image/jpeg', 1.0);

    const doc = new jsPDF(isHorizontal ? 'l' : 'p', 'px', 'a4');

    const pageWidth = doc.internal.pageSize.getWidth()
    const pageHeight = doc.internal.pageSize.getHeight()

    const widthRatio = (pageWidth-40) / canvas.width
    const heightRatio = (pageHeight-40) / canvas.height

    if(!isHorizontal) { // 纵向导出
      let ratio = widthRatio;
      let images = await createPages(image, {width: canvas.width, height: canvas.height}, (pageHeight-40)/ratio);

      images.forEach((item, index, arr) => {
        let canvasWidth = item.width * ratio;
        let canvasHeight = item.height * ratio;
        let marginX = (pageWidth - canvasWidth) / 2
        doc.addImage(item.img, 'JPEG', marginX, 20, canvasWidth, canvasHeight)
        if(index < arr.length-1) {
          doc.addPage();
        }
      })
      // doc.output('dataurlnewwindow')
      doc.save(pdfname + '.pdf')
    } else { // 横向导出
      let ratio = widthRatio > heightRatio ? heightRatio : widthRatio;
      let canvasWidth = canvas.width * ratio
      let canvasHeight = canvas.height * ratio

      let marginX = (pageWidth - canvasWidth) / 2
      let marginY = (pageHeight - canvasHeight) / 2

      doc.addImage(image, 'JPEG', marginX, marginY, canvasWidth, canvasHeight)
      // doc.output('dataurlnewwindow')
      doc.save(pdfname + '.pdf')
    }
  })

  // 生成图片
  function createPages(base64, imageSize, pageHeight) {
    return new Promise((resolve, reject) => {
      var img = new Image();
      img.src = base64;
      img.onload = function () {
        var res = [];
        var oCanvas = document.createElement('canvas');
        const ctx = oCanvas.getContext('2d');

        let length = Math.ceil(imageSize.height/pageHeight);
        for(var i = 0; i < length; i++) {
          let width = imageSize.width;
          let height = pageHeight;
          if(i == length-1) {
            height = imageSize.height-pageHeight*i;
          }
          oCanvas.width = width;
          oCanvas.height = height;
          ctx.drawImage(img, 0, pageHeight*i, width, height, 0, 0, width, height);
          var dataURL = oCanvas.toDataURL('image/png');
          res.push({
            img: dataURL,
            width, width,
            height: height
          });
        }
        resolve(res);
      }
    })
  }
}
